package com.exonline.back.filter;

import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
/**
 * @desc 全局异常处理过滤器
 * @author hbrj
 */
@WebFilter("/*")
public class GlobalExceptionFilter extends HttpFilter {
    ObjectMapper mapper = new ObjectMapper();
    @Override
    protected void doFilter(HttpServletRequest req, HttpServletResponse resp, FilterChain chain) throws IOException, ServletException {
        try {
            chain.doFilter(req, resp);
        } catch (NullPointerException e) {
            Map<String, Object> map = new HashMap<>();
            map.put("code", 500);
            map.put("msg", "服务器出现错误,请确认是否正确包含请求参数,错误信息:" + e.getMessage());
            map.put("data", e.getMessage());
            mapper.writeValue(resp.getWriter(), map);
            throw e;
        } catch (ServletException e) {
            Map<String, Object> map = new HashMap<>();
            map.put("code", 500);
            map.put("msg", "服务器出现错误:" + e.getClass().getName());
            map.put("data", e.getMessage());
            mapper.writeValue(resp.getWriter(), map);
            throw e;
        } catch (RuntimeException e) {
            Map<String, Object> map = new HashMap<>();
            map.put("code", 500);
            map.put("msg", "服务器出现错误:" + e.getClass().getName());
            map.put("data", e.getMessage());
            mapper.writeValue(resp.getWriter(), map);
            throw e;
        } catch (IOException e) {
            Map<String, Object> map = new HashMap<>();
            map.put("code", 503);
            map.put("msg", "服务器出现错误:" + e.getClass().getName());
            map.put("data", e.getMessage());
            mapper.writeValue(resp.getWriter(), map);
            throw e;
        }
    }
}

